<?php

function generateWechatPaySignature(
    string $appId,
    string $timestamp,
    string $nonceStr,
    string $prepayId,
    string $privateKey
): string {
    // 构造签名串
    $signatureString = sprintf("%s\n%s\n%s\nprepay_id=%s\n", 
        $appId, 
        $timestamp, 
        $nonceStr, 
        $prepayId
    );
    
    // 使用私钥进行SHA256 with RSA签名
    openssl_sign($signatureString, $signature, $privateKey, OPENSSL_ALGO_SHA256);
    
    // 对签名结果进行Base64编码
    return base64_encode($signature);
}

// 您的参数
$merchantId = '1900007291'; // 商户号
$serialNo = '408B07E79B8269FEC3D5D3E6AB8ED163A6A380DB'; // 证书序列号
$appId = 'wx2421b1c4370ec43b'; // 小程序AppID
$timestamp = 1554208460; // 当前时间戳time()
$nonceStr = '593BEC0C930BF1AFEB40B4A08C8FB242'; // 随机字符串
$prepayId = 'wx201410272009395522657a690389285100'; // prepay_id

// 示例私钥（实际使用时应该从文件中读取）
$privateKey = <<<EOD
-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAptpm+qvIDCh/9wjU26SQCK26ogYkBhDrYxnAaw2JbbBsp1oD
bHKk+1r381NeBUG2HEFAuU+Fr72u5ot3yKdzoF/FajAzQNKnm569/D3upKoi8mYB
aST15Uig8j8qoUW1U217LL0jEHlSnHV3lcaDTXqDpTRR4Bfz9IqOgJgFZ8/oTfEo
mSrjrLYef81Eyxr7ZIMQXEKKEK7V4UXKS0+/fDsiG/cXidhzt8UbTL9vqXqxM2+I
DImyO+FAc/tkBG55LmzxPto1Nq0WbnZzRM/wTzrd0I/8NlevxtFbphg4evlHjFNI
7+GrqR87ViEwuAJJ9Je5QQjct5YJfFRWiZ5CMQIDAQABAoIBAGBi/GhEgezcHIg1
ltlHaFlLGuxsRbUnYwM9phVxnXk7GJlYe2/TjpERjPkIqOC6hBwwadZjJORP3FCc
Mtc8PKRhjuZ377O7vU0915x2nnyLOGL1IE2AJ3iLi0ZFzTea0FPgg+5lWHM00s9F
YI6qPcGtS41M+xtMWwZiYE3TBBRibHiY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=
-----END RSA PRIVATE KEY-----
EOD;

// 计算签名
$signature = generateWechatPaySignature($appId, $timestamp, $nonceStr, $prepayId, $privateKey);

echo "生成的签名值: " . $signature . "\n";

// 验证签名是否正确（可选）
$publicKey = openssl_pkey_get_details(openssl_pkey_get_private($privateKey))['key'];
$isValid = openssl_verify(
    sprintf("%s\n%s\n%s\nprepay_id=%s\n", $appId, $timestamp, $nonceStr, $prepayId),
    base64_decode($signature),
    $publicKey,
    OPENSSL_ALGO_SHA256
);

echo "签名验证结果: " . ($isValid === 1 ? "成功" : "失败") . "\n";
?>